package org.acsis.covoiturage.frontend.exception;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.Globals;

public class ExceptionHandlerServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = -4515388409080268131L;
	private static Logger logger = Logger.getLogger(ExceptionHandlerServlet.class);
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			logger.debug("Handling exception in ErrorHandlerServlet");

			Throwable exception = null;

			// Check if struts has placed an exception object in request
			Object obj = request.getAttribute(Globals.EXCEPTION_KEY);

			if (obj == null) {
			// Since no struts exception is found,
			// check if a JSP exception is available in request.
			obj = request.getAttribute("javax.servlet.jsp.jspException");
			}

			if ((obj != null) && (obj instanceof Throwable)) {
			exception = (Throwable) obj;
			}

			if (logger.isDebugEnabled()) {
			logger.debug("Request URI: " + request.getAttribute("javax.servlet.forward.request_uri"));
			}

			// request uri containing the original URL value will be available
			// only on servers implementing servlet 2.4 spec
			String requestURI = (String) request.getAttribute("javax.servlet.forward.request_uri");

			logger.error("Exception while handling request: " + requestURI, exception);
			response.sendRedirect(requestURI);
			} catch (Exception e) {
			// Throwing exceptions from this method can result in request
			// going in to an infinite loop forwarding to the error servlet recursively.
			e.printStackTrace();
			}
	}
}
